<?php
/**
 * CEOfox
 *
 * @copyright  Copyright 2011-2012 CEOfox, Inc.
 * @license    http://ceofox.com/pages/license
 * @version    $Id: notification.class.php 37086 2013-05-24 09:40:17 $
 * @author     CEOfox, Inc.
 */
?>
<?php

defined('PHPFOX') or exit('NO DICE!');

class Follow_Service_Notifications extends Phpfox_Service
{
    public function __construct()
    {
        $this->_sTable = phpfox::getT('follow_notification');
    }
    public function deleteById($iId)
    {
        d($iId);
        
        return true;
    }
    public function getForBrowse($iPage = 0, $iPageSize= 10, $iUserId = 0)
    {
        $aNotifications = array();
        if(!$iUserId)
        {
            $iUserId = Phpfox::getUserId();
        }
        $iCnt = $this->database()->select('count(*)')
                ->from(Phpfox::getT('follow_notification'),'n')
                ->where('n.user_id = '.(int)$iUserId)
                ->execute('getSlaveField');
                
        $aRows = $this->database()->select('n.*,'.Phpfox::getUserField())
                ->from(Phpfox::getT('follow_notification'),'n')
                ->join(Phpfox::getT('user'),'u', 'u.user_id = n.user_id')
                ->where('n.user_id = '.(int)$iUserId)
                ->limit($iPage, $iPageSize, $iCnt)
                ->order('n.time_stamp DESC')
                ->execute('getSlaveRows');
        
        $sIds = '';
        foreach ($aRows as $aRow)
        {
            $sIds .= (int) $aRow['notification_id'] . ',';
            
            $iDate = Phpfox::getTime('dmy', $aRow['time_stamp']);        
                
            if ($iDate == Phpfox::getTime('dmy', PHPFOX_TIME))
            {
                $iDate = Phpfox::getPhrase('notification.today');
            }
            elseif ($iDate == Phpfox::getTime('dmy', (PHPFOX_TIME - 86400)))
            {
                $iDate = Phpfox::getPhrase('notification.yesterday');
            }
            else 
            {
                 $iDate = Phpfox::getTime(Phpfox::getParam('notification.notification_browse_messages'), $aRow['time_stamp']);
            }                        
            
            
            if($aRow['type_id'] != 'user_status')
            {
                if($aRow = $this->getItemInfo($aRow))
                {
                    
                    $aPart = explode('_', $aRow['type_id']);
                    $sFucntion = (isset($aPart[1]) && ($aPart[1] == 'comment')) ?  'getActivityFeedComment' : 'getActivityFeed'; 
                    if(!Phpfox::hasCallback($aPart[0], $sFucntion))
                    {
                        unset($aRows[$iKey]);
                        continue;
                    }
                    else
                    {
                        $aTemp = Phpfox::callback($aPart[0] . '.'.$sFucntion, $aRow);
                        //$aTemp['link'] = Phpfox::getLib('url')->makeUrl($aRow['user_name']);
                        $aTemp['link'] = $aTemp['feed_link'];
                        $aTemp['icon'] = $aTemp['feed_icon'];
                        $sTypeFollow = '';
                        if($aRow['profile_page_id'])
                        {
                            $sTypeFollow = Phpfox::getPhrase('follow.page');
                        }
                        
                        $aTemp['message'] = Phpfox::getPhrase('follow.typefollow_add_new_type_title', array('typefollow'=> $sTypeFollow, 'full_name' => Phpfox::getLib('parse.output')->shorten($aRow['full_name'], 35, '...'), 'type_item' => $aPart[0],'item_title' => Phpfox::getLib('parse.output')->shorten($aRow['follow_item_title'], Phpfox::getParam('notification.total_notification_title_length'), '...')));
                        $aNotifications[$iDate][] = array_merge($aTemp, $aRow);
                    }    
                }
                else
                {
                    unset($aRows[$iKey]);
                }
            }
            else
            {
                
                if($aRow = $this->getItemInfo($aRow))
                {
                    $aTemp = Phpfox::getService('user.callback')->getActivityFeedStatus($aRow);
                    $aTemp['link'] = $aTemp['feed_link'];
                    $aTemp['icon'] = $aTemp['feed_icon'];
                    $aTemp['message'] = Phpfox::getPhrase('follow.typefollow_add_new_status_title', array('full_name' => Phpfox::getLib('parse.output')->shorten($aRow['full_name'], Phpfox::getParam('notification.total_notification_title_length'), '...'), 'item_title' => Phpfox::getLib('parse.output')->shorten($aRow['follow_item_title'], Phpfox::getParam('notification.total_notification_title_length'), '...')));
                    $aNotifications[$iDate][] = array_merge($aTemp, $aRow);
                }
                else
                {
                    unset($aRows[$iKey]);
                }
            }
            /*
            if (substr($aRow['type_id'], 0, 8) != 'comment_' && !Phpfox::hasCallback($aRow['type_id'], 'getNotification'))
            {                
                $aRow['link'] = '#';
                $aRow['message'] = '1. Notification is missing a callback. [' . $aRow['type_id'] . '::getNotification]';
                    
                $aNotifications[$iDate][] = $aRow;
                
                continue;
            }
            
            if (substr($aRow['type_id'], 0, 8) == 'comment_' && substr($aRow['type_id'], 0, 12) != 'comment_feed' && !Phpfox::hasCallback(substr_replace($aRow['type_id'], '', 0, 8), 'getCommentNotification'))
            {
                $aRow['link'] = '#';
                $aRow['message'] = 'Notification is missing a callback. [' . substr_replace($aRow['type_id'], '', 0, 8) . '::getCommentNotification]';
                    
                $aNotifications[$iDate][] = $aRow;
                
                continue;                
            }
            
            if (($aCallBack = Phpfox::callback($aRow['type_id'] . '.getNotification', $aRow)))
            {     
                
                if (!isset($aCallBack['message']))
                {
                    $aRow['link'] = '#';
                    $aRow['message'] = 'Notification is missing a message/link param. [' . $aRow['type_id'] . '::getNotification]';                
                }

                $aNotifications[$iDate][] = array_merge($aRow, (array) $aCallBack);
            }
            
            */
        }
        
        $sIds = rtrim($sIds, ',');
        
        
        return array($iCnt, $aNotifications);
    }
    public function sendNotifications($iItemId, $sType, $aCallBack)
    {
        if(!$iItemId || !$sType)
        {
            return false;
        }
        $aPart = explode('_', $sType);
        if(isset($aPart[1]) && !empty($aPart[1]) && $aPart[1] != 'comment')
        {
            return false;
        }
        $iTempItemId = isset($aCallBack['item_id']) ? $aCallBack['item_id'] : Phpfox::getUserId();
        $sTempType = isset($aCallBack['module']) ? $aCallBack['module'] : 'user';
        list($iCnt,$aFollowers) = $this->getFollower($iTempItemId, 0, 0, $sTempType);
        
        if(!$iCnt)
        {
            return false;
        }
        $aNotifications = array();
        foreach($aFollowers as $iKey => $aRow)
        {
            $aNotifications[] = array(
                'item_id' => $iItemId,
                'type_id' => $sType, 
                'user_id' => $aRow['user_id'],
                'time_stamp' => PHPFOX_TIME,
            );
        }
        if(!empty($aNotifications))
        {
            $aField = array(
             'item_id',
             'type_id',
             'user_id',
             'time_stamp'
            );
            $this->database()->multiInsert(Phpfox::getT('follow_notification'), $aField, $aNotifications);
        }
    }
    public function getItemInfo($aRow = array())
    {
        $iNotificationId = $aRow['notification_id'];
        if(empty($aRow))
        {
            return false;
        }
        $aPart = explode('_', $aRow['type_id']);
        
        if($aRow['type_id'] == 'user_status')
        {
            $aTemp = $this->database()->select('f.*, ut.content as follow_item_title, '.Phpfox::getUserField()) 
                ->from(Phpfox::getT('feed'),'f')
                ->join(Phpfox::getT('user'),'u', 'f.user_id = u.user_id')
                ->join(Phpfox::getT('user_status'),'ut','ut.user_id = u.user_id')
                ->where('f.item_id = '.(int)$aRow['item_id'] .' AND f.type_id = "'.$aRow['type_id'].'"')
                ->execute('getSlaveRow');
            $aTemp['notification_id'] = $iNotificationId;
            
        }
        else
        {
            if(isset($aPart[1]) && !empty($aPart[1]) && $aPart[1] != 'comment')
            {
                return false;
            }
            //$aPart[0] = (($aPart[0] == 'pages') ? 'page': $aPart[0]);
            $sTableItem = $aPart[0];
            $sField = $aPart[0];
            if(in_array($aPart[0], array('pages', 'event')))
            {
                if(isset($aPart[1]) && $aPart[1] == 'comment')
                {
                    
                    $sTableItem = $aPart[0].'_feed_'.$aPart[1];
                    $sField = 'feed_comment';
                }
            }
            
            $aTemp = $this->database()->select('f.*, '.((isset($aPart[1]) && $aPart[1] == 'comment') ? 'item.content as follow_item_title': 'item.title as follow_item_title').', '.Phpfox::getUserField()) 
                ->from(Phpfox::getT('feed'),'f')
                ->join(Phpfox::getT('user'),'u', 'f.user_id = u.user_id')
                ->join(Phpfox::getT($sTableItem),'item', 'item.'.$sField.'_id = f.item_id')
                ->where('f.item_id = '.(int)$aRow['item_id'] .' AND f.type_id = "'.$aRow['type_id'].'"')
                ->execute('getSlaveRow');    
            $aTemp['notification_id'] = $iNotificationId;
            
        }
        if($aTemp['profile_page_id'] > 0)
        {
            $aTemp['avatar_link'] = Phpfox::getService('pages')->getUrl($aTemp['profile_page_id']);
        }
        else
        {
            $aTemp['avatar_link'] = Phpfox::getLib('url')->makeUrl($aTemp['user_name']);
        }
        return ($aTemp) ? $aTemp : false;
    }
    
    public function getNotifications($iUserId = 0, $iPage = 1, $iPageSize = 5)
    {
        $aNotifications = array();
        if(!$iUserId)
        {
            return false;
        }
        
        $iCnt = $this->database()->select('count(*)')
                ->from(Phpfox::getT('follow_notification'),'n')
                ->where('n.user_id = '.(int)$iUserId)
                ->execute('getSlaveField');
                
        $aRows = $this->database()->select('n.*,'.Phpfox::getUserField())
                ->from(Phpfox::getT('follow_notification'),'n')
                ->join(Phpfox::getT('user'),'u', 'u.user_id = n.user_id')
                ->where('n.user_id = '.(int)$iUserId)
                ->limit($iPage, $iPageSize, $iCnt)
                ->order('n.time_stamp DESC')
                ->execute('getSlaveRows');
        
        if(!$aRows)
        {
            return false;
        }
        foreach($aRows as $iKey => $aRow)    
        {
            if($aRow['type_id'] != 'user_status')
            {
                if($aRow = $this->getItemInfo($aRow))
                {
                    $aPart = explode('_', $aRow['type_id']);
                    $sFucntion = (isset($aPart[1]) && ($aPart[1] == 'comment')) ?  'getActivityFeedComment' : 'getActivityFeed'; 
                    if(!Phpfox::hasCallback($aPart[0], $sFucntion))
                    {
                        unset($aRows[$iKey]);
                        continue;
                    }
                    else
                    {
                        $aTemp = Phpfox::callback($aPart[0] . '.'.$sFucntion, $aRow);
                        //$aTemp['link'] = Phpfox::getLib('url')->makeUrl($aRow['user_name']);
                        $aTemp['link'] = $aTemp['feed_link'];
                        $aTemp['icon'] = $aTemp['feed_icon'];
                        $sTypeFollow = '';
                        if($aRow['profile_page_id'])
                        {
                            $sTypeFollow = Phpfox::getPhrase('follow.page');
                        }
                        
                        $aTemp['message'] = Phpfox::getPhrase('follow.typefollow_add_new_type_title', array('typefollow'=> $sTypeFollow, 'full_name' => Phpfox::getLib('parse.output')->shorten($aRow['full_name'], 35, '...'), 'type_item' => $aPart[0],'item_title' => Phpfox::getLib('parse.output')->shorten($aRow['follow_item_title'], Phpfox::getParam('notification.total_notification_title_length'), '...')));
                        $aNotifications[] = array_merge($aTemp, $aRow);
                    }    
                }
                else
                {
                    unset($aRows[$iKey]);
                }
            }
            else
            {
                
                if($aRow = $this->getItemInfo($aRow))
                {
                    $aTemp = Phpfox::getService('user.callback')->getActivityFeedStatus($aRow);
                    $aTemp['link'] = $aTemp['feed_link'];
                    $aTemp['icon'] = $aTemp['feed_icon'];
                    $aTemp['message'] = Phpfox::getPhrase('follow.typefollow_add_new_status_title', array('full_name' => Phpfox::getLib('parse.output')->shorten($aRow['full_name'], Phpfox::getParam('notification.total_notification_title_length'), '...'), 'item_title' => Phpfox::getLib('parse.output')->shorten($aRow['follow_item_title'], Phpfox::getParam('notification.total_notification_title_length'), '...')));
                    $aNotifications[] = array_merge($aTemp, $aRow);
                }
                else
                {
                    unset($aRows[$iKey]);
                }
            }
        }
        return $aNotifications;    
    }
}
?>
